<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */

namespace app\result;

use app\model\coupon\Coupon;
use app\model\coupon\CouponUser;
use app\model\user\User;

class CouponResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Coupon();
    }

    public function api_list($args = [], $user_id = 0): array
    {
        $from = $args['from'] ?? 'index';
        $style = [
            'paddingTop' => '7',
            'background' => '#ffffff'
        ];
        $where = [['status', '=', 1]];
        if ($user_id) {
            $myCouponIds = (new CouponUser())->data_list_nopage(['user_id' => $user_id], 'coupon_id');
            if ($myCouponIds) {
                $myCouponIds = array_column($myCouponIds, null, 'coupon_id');
            }
            if ($from == 'index') {
                $where[] = ['coupon_id', 'not in', array_keys($myCouponIds)];
            }
        }

        $field = 'coupon_id,name,color,coupon_type,reduce_price,discount,min_price,expire_type,expire_day,start_time,end_time,apply_range,total_num,status';
        $data = $this->model->data_list_nopage($where, $field, 'sort desc, coupon_id desc');

        if ($data) {
            foreach ($data as &$v) {
                $v['state'] = [
                    'text' => '',
                    'value' => $v['status']
                ];
                $v['color'] = [
                    'text' => $v['color'],
                    'value' => 30
                ];
                $v['enable'] = 1;
                if (!empty($myCouponIds[$v['coupon_id']])) {
                    $v['state'] = [
                        'text' => '已领取',
                        'value' => 20
                    ];
                    $v['color'] = [
                        'text' => 'gray',
                        'value' => 20
                    ];
                    $v['enable'] = 0;
                }

                if ($v['coupon_type'] == 10) {
                    $v['coupon_type'] = [
                        'text' => '满减券',
                        'value' => 10
                    ];
                } else {
                    $v['coupon_type'] = [
                        'text' => '折扣券',
                        'value' => 20
                    ];
                }

                $v['apply_range'] = [
                    'text' => '全场通用',
                    'value' => 10
                ];
                $v['start_time'] = [
                    'text' => date('Y/m/d', $v['start_time']),
                    'value' => $v['start_time']
                ];
                $v['end_time'] = [
                    'text' => date('Y/m/d', $v['end_time']),
                    'value' => $v['end_time']
                ];
            }
            unset($v);
        }
        usort($data, function ($a, $b) {
            return $b['enable'] - $a['enable'];
        });
        //首页组件使用
        if ($from == 'index') {
            $data = $data ? array_values(array_slice($data, 0, 3)) : [];
        }
        // 全部接口
        if ($from == 'all') {
            return self::success_return('success', [
                'list' => $data
            ]);
        }

        return [
            'style' => $style,
            'data_list' => $data ?? []
        ];

    }

    // 更新过期优惠券状态
    public static function update_expire_coupon($user_id)
    {
        $ckey = 'coupon_user_expire_' . $user_id;
        if (cache($ckey)) {
            return;
        }
        cache($ckey, 1, 3600);
        $model = new CouponUser();
        $model->where('user_id', $user_id)
            ->where('status', 0)
            ->where('end_time', '<', time())
            ->update(['status' => 2]);
    }

    public function order_coupon($user_id, $order_pay_price)
    {
        $where = [];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['status', '=', 0];
        $where[] = ['start_time', '<', time()];
        $where[] = ['end_time', '>', time()];
        $where[] = ['min_price', '<=', $order_pay_price];


        $model = new CouponUser();
        $data = $model->data_list_nopage($where, '*', 'end_time asc');
        if ($data) {
            foreach ($data as &$v) {
                $v['state'] = [
                    'text' => '',
                    'value' => ($v['status'] == 0 && $v['start_time'] < time() && $v['end_time'] > time())
                ];
                $v['color'] = [
                    'text' => $v['color'],
                    'value' => 30
                ];
                if ($v['coupon_type'] == 10) {
                    $v['coupon_type'] = [
                        'text' => '满减券',
                        'value' => 10
                    ];
                } else {
                    $v['coupon_type'] = [
                        'text' => '折扣券',
                        'value' => 20
                    ];
                    //抵扣金额计算
                    $v['reduce_price'] = bcmul((10 - $v['discount']) / 10, $order_pay_price, 2);
                }
                $v['apply_range'] = [
                    'text' => '全场通用',
                    'value' => 10
                ];
                $v['start_time'] = [
                    'text' => date('Y/m/d', $v['start_time']),
                    'value' => $v['start_time']
                ];
                $v['end_time'] = [
                    'text' => date('Y/m/d', $v['end_time']),
                    'value' => $v['end_time']
                ];

            }
            unset($v);
            //按折扣券排序
            usort($data, function ($a, $b) {
                return $b['reduce_price'] - $a['reduce_price'];
            });
        }
        return $data;
    }

    public function api_my_list($user_id, $args = [])
    {
        $status = intval($args['status'] ?? '0');
        $where = [];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['status', '=', $status];

        $model = new CouponUser();
        $data = $model->data_list_nopage($where);
        if ($data) {
            foreach ($data as &$v) {
                $v['state'] = [
                    'text' => '',
                    'value' => ($v['status'] == 0 && $v['start_time'] < time() && $v['end_time'] > time())
                ];
                $v['color'] = [
                    'text' => $v['color'],
                    'value' => 30
                ];
                if ($v['coupon_type'] == 10) {
                    $v['coupon_type'] = [
                        'text' => '满减券',
                        'value' => 10
                    ];
                } else {
                    $v['coupon_type'] = [
                        'text' => '折扣券',
                        'value' => 20
                    ];
                }
                $v['apply_range'] = [
                    'text' => '全场通用',
                    'value' => 10
                ];
                $v['start_time'] = [
                    'text' => date('Y/m/d', $v['start_time']),
                    'value' => $v['start_time']
                ];
                $v['end_time'] = [
                    'text' => date('Y/m/d', $v['end_time']),
                    'value' => $v['end_time']
                ];

            }
            unset($v);
        }
        return self::success_return('success', [
            'list' => $data ?? []
        ]);
    }

    public function api_detail($args = []): array
    {
        return self::success_return('success');
    }

    public function api_get_coupon($user_id, $args = []): array
    {
        $coupon_id = $args['coupon_id'] ?? 0;
        $model = new Coupon();
        $data = $model->data_get(['coupon_id' => $coupon_id]);
        if (!$data) {
            return self::error_return("优惠券不存在");
        }
        if ($data['status'] != 1) {
            return self::error_return("优惠券已失效");
        }
        if ($data['total_num'] <= $data['get_num']) {
            return self::error_return("优惠券已领完");
        }
        $modelCouponUser = new CouponUser();
        if ($modelCouponUser->data_get(['coupon_id' => $coupon_id, 'user_id' => $user_id])) {
            return self::error_return("优惠券已领取");
        }
        $baseData = [
            'coupon_id' => $coupon_id,
            'user_id' => $user_id,
            'status' => 0,
            'name' => $data['name'],
            'color' => $data['color'],
            'coupon_type' => $data['coupon_type'],
            'reduce_price' => $data['reduce_price'],
            'discount' => $data['discount'],
            'min_price' => $data['min_price'],
            'expire_type' => $data['expire_type'],
            'expire_day' => $data['expire_day'],
            'apply_range' => $data['apply_range'],
        ];
        if ($data['expire_type'] == 20) {
            $baseData['start_time'] = $data['start_time'];
            $baseData['end_time'] = $data['end_time'];
        } elseif ($data['expire_type'] == 10) {
            $baseData['start_time'] = time();
            $baseData['end_time'] = time() + $data['expire_day'] * 86400;
        }
        $res = $modelCouponUser->data_add($baseData);
        if (!$res) {
            return self::error_return("领取失败");
        }
        $model->data_update(['coupon_id' => $coupon_id], ['get_num' => $data['get_num'] + 1]);
        return self::success_return("领取成功");
    }

    public function list($args = [])
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $status = intval($args['status'] ?? 0);
        $coupon_type = intval($args['coupon_type'] ?? 0);
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['name', 'like', '%' . trim($args['keyword']) . '%'];
        }
        if ($status) {
            $where[] = ['status', '=', $status];
        }
        if ($coupon_type) {
            $where[] = ['coupon_type', '=', $coupon_type];
        }
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', 'coupon_id desc', $page, $pageSize);
        if ($data) {
            foreach ($data as &$item) {
                $item['coupon_type_desc'] = $item['coupon_type'] == 10 ? '满减券' : '折扣券';//优惠券类型：10=满减，20=折扣
                $item['expire_type_desc'] = $item['expire_type'] == 10 ? '领取后' . $item['expire_day'] . '天有效' : '有效期内使用';
                $item['startTime'] = date('Y-m-d H:i:s', $item['start_time']);
                $item['endTime'] = date('Y-m-d H:i:s', $item['end_time']);
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }

    public function get($args = [])
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(['coupon_id' => $id]);
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $data['start_time'] = date('Y-m-d H:i:s', $data['start_time']);
        $data['end_time'] = date('Y-m-d H:i:s', $data['end_time']);
        return $this->success_return('success', [
            'info' => $data
        ]);
    }

    public function save_data($args): array
    {
        $id = intval($args['coupon_id'] ?? 0);
        $rules = [
            ['name', 'empty|max:20', '请填写名称|名称长度不能超过20个字符'],
            ['start_time', 'empty', '请选择开始时间'],
            ['end_time', 'empty', '请选择结束时间'],
            ['color', 'empty', '请选择颜色'],
            ['coupon_type', 'empty', '请选择优惠券类型'],
            // ['reduce_price', 'empty', '请填写满减金额'],
            //['discount', 'empty', '请填写折扣'],
            ['min_price', 'empty', '请填写最低消费金额'],
            ['expire_type', 'empty', '请选择有效期类型'],
            //['expire_day', 'empty', '请填写有效期天数'],
        ];
        $check = check_param($args, $rules);
        if ($check['status'] != 0) {
            return self::error_return($check['msg']);
        }
        if ($args['coupon_type'] == 10 && empty($args['reduce_price'])) {
            return self::error_return('满减金额不能为空');
        } elseif ($args['coupon_type'] == 20 && empty($args['discount'])) {
            return self::error_return('折扣不能为空');
        }

        $baseData = [
            'name' => $args['name'],
            'color' => $args['color'],
            'coupon_type' => $args['coupon_type'],
            'reduce_price' => $args['reduce_price'],
            'discount' => $args['discount'],
            'min_price' => $args['min_price'],
            'expire_type' => $args['expire_type'],
            'expire_day' => $args['expire_day'],
            'apply_range' => $args['apply_range'],
            'total_num' => $args['total_num'],
            'sort' => $args['sort'],
            'status' => $args['status'],
            'start_time' => strtotime($args['start_time']),
            'end_time' => strtotime($args['end_time']),
        ];
        if ($id) {
            $this->model->data_update(['coupon_id' => $id], $baseData);
        } else {
            $this->model->data_add($baseData);
        }
        return $this->success_return('保存成功');
    }

    public function set_status($args)
    {
        $id = intval($args['id'] ?? 0);
        $status = $this->model->get_value(['coupon_id' => $id], 'status');
        $res = (new Coupon())->data_update(['coupon_id' => $id], ['status' => $status == 1 ? -1 : 1]);
        return $this->success_return('保存成功');
    }

    public function del_data($args): array
    {
        $id = intval($args['id'] ?? 0);
        $res = $this->model->data_del(['coupon_id' => $id]);
        return $this->success_return('已删除');
    }

    //领取记录
    public function coupon_log($args = [])
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $status = trim($args['status'] ?? '');
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['name', 'like', '%' . trim($args['keyword']) . '%'];
        }
        if (is_numeric($status)) {
            $where[] = ['status', '=', $status];
        }
        $model = new CouponUser();
        $total = $model->data_count($where);
        $data = $model->data_list($where, '*', 'coupon_id desc', $page, $pageSize)?->toArray();
        if ($data) {
            $statusArr = [
                2 => '已失效',
                0 => '未使用',
                1 => '已使用',
            ];
            $users = (new User())->data_list_nopage(['user_id' => array_column($data, 'user_id')], 'user_id,username,account');
            $users = $users ? array_column($users, null, 'user_id') : [];
            foreach ($data as &$item) {
                $item['coupon_type_desc'] = $item['coupon_type'] == 10 ? '满减券' : '折扣券';//优惠券类型：10=满减，20=折扣
                $item['expire_type_desc'] = $item['expire_type'] == 10 ? '领取后' . $item['expire_day'] . '天有效' : '有效期内使用';
                $item['startTime'] = date('Y-m-d H:i:s', $item['start_time']);
                $item['endTime'] = date('Y-m-d H:i:s', $item['end_time']);
                $item['status_desc'] = $statusArr[$item['status']];
                $item['user_info'] = $users[$item['user_id']] ?? [];
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }
}
